import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:grint/bloc/record_cubit.dart';
import 'package:grint/constant/colors.dart';
import 'package:grint/constant/icon_font.dart';
import 'package:grint/widget/black_button.dart';
import 'package:grint/widget/my_text.dart';
import 'dart:io';

import 'package:url_launcher/url_launcher.dart';

class RecordPage extends StatefulWidget {
  const RecordPage({super.key});

  @override
  State<RecordPage> createState() => _RecordPageState();
}

class _RecordPageState extends State<RecordPage> {
  final TextEditingController _contentController = TextEditingController();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _contentController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => RecordCubit(),
      child: Scaffold(
        backgroundColor: AppColors.lightBlue,
        body: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/commonBg.png'),
              fit: BoxFit.cover,
            ),
          ),
          child: SafeArea(
            bottom: false,
            child: BlocBuilder<RecordCubit, RecordState>(
              builder: (context, state) {
                if (_contentController.text != state.recordContent) {
                  _contentController.text = state.recordContent;
                }

                final isToday = _isSameDay(state.selectedDate, DateTime.now());
                final isCheckedIn = context.read<RecordCubit>().isCheckedIn(
                  state.selectedDate,
                );
                final canEdit = isToday && !isCheckedIn;

                return SingleChildScrollView(
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    child: Column(
                      children: [
                        // 顶部导航栏
                        Row(
                          children: [
                            BlackButton(
                              icon: IconFontIcons.iconArrowLeft,
                              onTap: () {
                                context.pop();
                              },
                            ),
                            SizedBox(width: 16.w),
                            Expanded(
                              child: Center(
                                child: MyText(
                                  text: 'Record',
                                  type: TextType.rubik,
                                  fontSize: 28.sp,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.black87,
                                ),
                              ),
                            ),
                            SizedBox(width: 36.w),
                          ],
                        ),

                        SizedBox(height: 20.h),

                        Container(
                          width: double.infinity,
                          decoration: BoxDecoration(
                            color: AppColors.white,
                            borderRadius: BorderRadius.circular(20.r),
                            border: Border.all(
                              color: AppColors.border,
                              width: 3.w,
                            ),
                          ),
                          padding: EdgeInsets.all(20.w),
                          child: Column(
                            children: [
                              // 年份选择
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  SizedBox(width: 20.w),
                                  GestureDetector(
                                    onTap: () {
                                      context.read<RecordCubit>().changeYear(
                                        state.currentYear - 1,
                                      );
                                    },
                                    child: Icon(
                                      Icons.chevron_left,
                                      size: 24.sp,
                                      color: AppColors.black,
                                    ),
                                  ),
                                  Spacer(),
                                  MyText(
                                    text: state.currentYear.toString(),
                                    type: TextType.rubik,
                                    fontSize: 14.sp,
                                    fontWeight: FontWeight.w600,
                                    color: AppColors.black,
                                  ),
                                  Spacer(),
                                  GestureDetector(
                                    onTap: () {
                                      context.read<RecordCubit>().changeYear(
                                        state.currentYear + 1,
                                      );
                                    },
                                    child: Icon(
                                      Icons.chevron_right,
                                      size: 24.sp,
                                      color: AppColors.black,
                                    ),
                                  ),
                                  SizedBox(width: 20.w),
                                ],
                              ),

                              // 月份选择
                              Padding(
                                padding: EdgeInsets.only(top: 6.h),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    GestureDetector(
                                      onTap: () {
                                        final newMonth =
                                            state.currentMonth.month - 1;
                                        if (newMonth < 1) {
                                          context
                                              .read<RecordCubit>()
                                              .changeYear(
                                                state.currentYear - 1,
                                              );
                                          context
                                              .read<RecordCubit>()
                                              .changeMonth(12);
                                        } else {
                                          context
                                              .read<RecordCubit>()
                                              .changeMonth(newMonth);
                                        }
                                      },
                                      child: Icon(
                                        Icons.chevron_left,
                                        size: 24.sp,
                                        color: AppColors.black,
                                      ),
                                    ),
                                    SizedBox(width: 8.w),
                                    MyText(
                                      text: _getMonthName(
                                        state.currentMonth.month,
                                      ),
                                      type: TextType.rubik,
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.w600,
                                      color: AppColors.black,
                                    ),
                                    SizedBox(width: 8.w),
                                    GestureDetector(
                                      onTap: () {
                                        final newMonth =
                                            state.currentMonth.month + 1;
                                        if (newMonth > 12) {
                                          context
                                              .read<RecordCubit>()
                                              .changeYear(
                                                state.currentYear + 1,
                                              );
                                          context
                                              .read<RecordCubit>()
                                              .changeMonth(1);
                                        } else {
                                          context
                                              .read<RecordCubit>()
                                              .changeMonth(newMonth);
                                        }
                                      },
                                      child: Icon(
                                        Icons.chevron_right,
                                        size: 24.sp,
                                        color: AppColors.black,
                                      ),
                                    ),
                                  ],
                                ),
                              ),

                              Column(children: _buildRiLi(context, state)),
                            ],
                          ),
                        ),

                        SizedBox(height: 16.h),

                        // 照片记录卡片
                        Container(
                          width: double.infinity,
                          height: 216.h,
                          padding: EdgeInsets.symmetric(
                            horizontal: 7.w,
                            vertical: 9.h,
                          ),
                          decoration: BoxDecoration(
                            color: AppColors.white,
                            borderRadius: BorderRadius.circular(24.r),
                          ),
                          child: Container(
                            // 第二个盒子
                            padding: EdgeInsets.symmetric(
                              horizontal: 14.w,
                              vertical: 9.h,
                            ),
                            decoration: BoxDecoration(
                              color: Color(0xFFF6F6F6),
                              borderRadius: BorderRadius.circular(24.r),
                            ),
                            child: Container(
                              // 第三个盒子
                              width: double.infinity,
                              decoration: BoxDecoration(
                                color: AppColors.white,
                                borderRadius: BorderRadius.circular(24.r),
                              ),
                              child: AbsorbPointer(
                                absorbing: !canEdit,
                                child: GestureDetector(
                                  onTap: () async {
                                    if (canEdit) {
                                      await context
                                          .read<RecordCubit>()
                                          .pickAndSaveImage(context);
                                    }
                                  },
                                  child: Container(
                                    width: double.infinity,
                                    height: 140.h,
                                    child:
                                        state.selectedImagePath == null
                                            ? Column(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.center,
                                              children: [
                                                Icon(
                                                  IconFontIcons.iconUpload,
                                                  size: 48.sp,
                                                  color: AppColors.black,
                                                ),
                                                SizedBox(height: 12.h),
                                                MyText(
                                                  text:
                                                      'Take photos to record the changes in your teeth',
                                                  type: TextType.miSans,
                                                  fontSize: 12.sp,
                                                  color: AppColors.black,
                                                  textAlign: TextAlign.center,
                                                ),
                                              ],
                                            )
                                            : Stack(
                                              alignment: Alignment.topRight,
                                              children: [
                                                ClipRRect(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                        16.r,
                                                      ),
                                                  child: Image.file(
                                                    File(
                                                      state.selectedImagePath!,
                                                    ),
                                                    width: double.infinity,
                                                    fit: BoxFit.cover,
                                                  ),
                                                ),
                                                if (canEdit)
                                                  GestureDetector(
                                                    onTap: () {
                                                      context
                                                          .read<RecordCubit>()
                                                          .clearSelectedImage();
                                                    },
                                                    child: Container(
                                                      decoration: BoxDecoration(
                                                        color: Colors.white,
                                                        shape: BoxShape.circle,
                                                      ),
                                                      padding: EdgeInsets.all(
                                                        4.w,
                                                      ),
                                                      margin: EdgeInsets.all(
                                                        4.w,
                                                      ),
                                                      child: Icon(
                                                        Icons.close,
                                                        size: 18.sp,
                                                        color: Colors.red,
                                                      ),
                                                    ),
                                                  ),
                                              ],
                                            ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                        SizedBox(height: 16.h),
                        // 记录内容卡片
                        Container(
                          width: double.infinity,
                          height: 156.h,
                          decoration: BoxDecoration(
                            color: AppColors.white,
                            borderRadius: BorderRadius.circular(24.r),
                          ),
                          padding: EdgeInsets.symmetric(
                            horizontal: 8.w,
                            vertical: 8.h,
                          ),
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 15.w,
                              vertical: 12.h,
                            ),
                            decoration: BoxDecoration(
                              color: Color(0xFFF6F6F6),
                              borderRadius: BorderRadius.circular(24.r),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                TextField(
                                  controller: _contentController,
                                  maxLines: 4,
                                  enabled: canEdit,
                                  decoration: InputDecoration(
                                    hintText:
                                        (!isToday && !isCheckedIn)
                                            ? 'No record for this day'
                                            : 'Record Content',
                                    border: InputBorder.none,
                                  ),
                                  style: TextStyle(
                                    fontSize: 12.sp,
                                    color: AppColors.black,
                                  ),
                                  onChanged: (value) {
                                    context
                                        .read<RecordCubit>()
                                        .updateRecordContent(value);
                                  },
                                ),
                              ],
                            ),
                          ),
                        ),

                        SizedBox(height: 20.h),

                        // 打卡按钮
                        GestureDetector(
                          onTap: () async {
                            if (canEdit) {
                              final cubit = context.read<RecordCubit>();
                              final result = await cubit.checkInWithContent();
                              if (result && mounted) {
                                // 清空输入框和图片
                                _contentController.clear();
                                cubit.clearSelectedImage();

                                final today = DateTime.now();
                                await cubit.selectDate(today);
                              }
                            }
                          },
                          child: Container(
                            width: double.infinity,
                            height: 48.h,
                            decoration: BoxDecoration(
                              color:
                                  canEdit
                                      ? AppColors.black
                                      : Colors.grey.shade400,
                              borderRadius: BorderRadius.circular(24.r),
                            ),
                            child: Center(
                              child: MyText(
                                text:
                                    canEdit
                                        ? 'Record Today'
                                        : isCheckedIn
                                        ? 'Checked In'
                                        : 'Select Today',
                                type: TextType.rubik,
                                fontSize: 16.sp,
                                fontWeight: FontWeight.bold,
                                color: AppColors.white,
                              ),
                            ),
                          ),
                        ),

                        SizedBox(height: 10.h),

                        Center(
                          child: GestureDetector(
                            onTap: () async {
                              await launchUrl(
                                Uri.parse(
                                  'https://www.freeprivacypolicy.com/live/56bca466-eac6-41d2-8223-bb76973f5503',
                                ),
                                mode: LaunchMode.inAppBrowserView,
                              );
                            },
                            child: MyText(
                              text: 'EULA',
                              type: TextType.miSans,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w400,
                              color: AppColors.black,
                              decoration: TextDecoration.underline,
                            ),
                          ),
                        ),

                        SizedBox(height: 60.h),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  List<Widget> _buildRiLi(BuildContext context, RecordState state) {
    final recordCubit = context.read<RecordCubit>();
    final daysInMonth = recordCubit.getDaysInCurrentMonth();
    final firstDayOfWeek = recordCubit.getFirstDayOfMonth();

    final List<Widget> rows = [];

    // 固定显示5排日历
    int dayCounter = 1;

    for (int row = 0; row < 5; row++) {
      final List<Widget> rowChildren = [];

      // 每行7个格子
      for (int col = 0; col < 7; col++) {
        if (dayCounter <= daysInMonth) {
          // 有效的日期
          final DateTime date = DateTime(
            state.currentYear,
            state.currentMonth.month,
            dayCounter,
          );
          final bool isToday = _isSameDay(date, DateTime.now());
          final bool isSelected = _isSameDay(state.selectedDate, date);
          final bool hasRecord = recordCubit.isCheckedIn(date);
          final bool isFutureDate = date.isAfter(DateTime.now());
          final bool isSelectable = !isFutureDate;

          rowChildren.add(
            GestureDetector(
              onTap:
                  isSelectable
                      ? () async {
                        await recordCubit.selectDate(date);
                      }
                      : null,
              child: Container(
                width: 36.w,
                height: 36.w,
                margin: EdgeInsets.all(2.w),
                decoration: BoxDecoration(
                  color:
                      isSelected
                          ? AppColors.blue
                          : isFutureDate
                          ? Colors.grey.shade300
                          : Colors.grey.shade200,
                  border:
                      isToday && !isSelected
                          ? Border.all(color: AppColors.lightBlue, width: 1.5)
                          : null,
                ),
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    MyText(
                      text: dayCounter.toString(),
                      type: TextType.miSans,
                      fontSize: 12.sp,
                      fontWeight: isToday ? FontWeight.bold : FontWeight.normal,
                      color:
                          isSelected
                              ? AppColors.black
                              : isFutureDate
                              ? Colors.grey.shade500
                              : AppColors.black,
                    ),
                    if (hasRecord)
                      Positioned(
                        bottom: 2.h,
                        child: Container(
                          width: 3.w,
                          height: 3.w,
                          decoration: BoxDecoration(
                            color:
                                isSelected ? AppColors.white : AppColors.blue,
                            shape: BoxShape.circle,
                          ),
                        ),
                      ),
                  ],
                ),
              ),
            ),
          );
          dayCounter++;
        } else {
          rowChildren.add(
            Container(
              width: 36.w,
              height: 36.w,
              margin: EdgeInsets.all(2.w),
              decoration: BoxDecoration(color: Colors.grey.shade200),
            ),
          );
        }
      }

      // 添加行
      rows.add(
        Padding(
          padding: EdgeInsets.symmetric(vertical: 0.5.h),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: rowChildren,
          ),
        ),
      );
    }

    return rows;
  }

  bool _isSameDay(DateTime date1, DateTime date2) {
    return date1.year == date2.year &&
        date1.month == date2.month &&
        date1.day == date2.day;
  }

  String _getMonthName(int month) {
    switch (month) {
      case 1:
        return 'Jan';
      case 2:
        return 'Feb';
      case 3:
        return 'Mar';
      case 4:
        return 'Apr';
      case 5:
        return 'May';
      case 6:
        return 'Jun';
      case 7:
        return 'Jul';
      case 8:
        return 'Aug';
      case 9:
        return 'Sep';
      case 10:
        return 'Oct';
      case 11:
        return 'Nov';
      case 12:
        return 'Dec';
      default:
        return '';
    }
  }
}
